package com.macro.mall.task;

import cn.hutool.core.date.DateUtil;
import com.macro.mall.bean.entity.OdrOrder;
import com.macro.mall.bean.vo.OrderStatusUpdateReqVO;
import com.macro.mall.bean.vo.QueryOdrOrderReqVO;
import com.macro.mall.bean.vo.ResposeListVO;
import com.macro.mall.service.OdrOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;

/**
 * @author super
 * @title: TaskProcessor
 * @description: TODO 订单关闭处理器
 * @date 2020/9/22 11:02
 */


@Slf4j
@Configuration
@EnableScheduling
public class CloseOrderTaskProcessor {

    private static final String KEY = "ORDER_CLOSE";
    @Autowired
    OdrOrderService odrOrderService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Scheduled(cron = "0 */5 * * * ?")
    public void orderClose() {
        log.info(new Date() + "  >>cron执行-关闭超时支付订单定时任务启动 Timer begin...");
        try {
            ValueOperations objOps = redisTemplate.opsForValue();
            boolean bSet = objOps.setIfAbsent(KEY, "processing");
            if (!bSet) {
                String message = "processor is running, cannot start again.";
                log.error(message + " the key is redis is :" + KEY);
                return;
            }
            QueryOdrOrderReqVO queryOdrOrderReqVO = QueryOdrOrderReqVO.builder()
                    .orderStatus("000")
                    .payEffect(DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss"))
                    .build();
            ResposeListVO<OdrOrder> odrOrderResposeListVO = odrOrderService.queryOdrOrderList(queryOdrOrderReqVO);
            for (OdrOrder result : odrOrderResposeListVO.getResult()) {
                log.info("orderClose ~~~~~~~~~~~~~~~~~~~~~~~~~~ orderid = ("+result.getOrderId()+")");
                odrOrderService.statusUpdate(OrderStatusUpdateReqVO.builder()
                        .orderId(result.getOrderId())
                        .preStatus("000")
                        .targetStatus("001")
                        .build());
            }
        } catch (Exception e) {
            log.error("orderClose ~~~~~~~~~~~~~~~~~~~~~~~~~~", e);
        } finally {
            log.info(new Date() + "  >>cron执行-关闭超时支付订单定时任务 Timer end.");
            Boolean delete = redisTemplate.delete(KEY);
        }

    }


}
